package com.wmlt.dao.impl;

import com.wmlt.dao.UserDao;
import com.wmlt.entity.Article;
import com.wmlt.entity.User;
import com.wmlt.util.JdbcUtil;
import com.wmlt.util.RandomUserNameUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class UserDaoImpl extends JdbcUtil implements UserDao {

    String sql = "";
    int result = 0;//0已注册，1未注册，2注册成功
    Connection connection = null;
    PreparedStatement prea = null;
    ResultSet res = null;

    /**
     * @description: QQ注册
     * @param: User
     * @return: User
     * @author liyuxiang
     * @date: 2021/3/22 9:00 下午
     */
    @Override
    public User qqRegister(User user) {
        User users = null;
        System.out.println(user.getUserQqcountId());
        connection = JdbcUtil.getConnection();
        try {
            sql = "select * from User where qqcount_id=?";
            prea = connection.prepareStatement(sql);
            prea.setString(1, user.getUserQqcountId());
            res = prea.executeQuery();
            while (res.next()) {
                users = new User();
                users = new User(res.getString("user_id"), res.getString("username"), null, res.getString("sex"), res.getString("mobile"), res.getString("qqcount_id"), res.getString("create_time"), res.getString("user_img"), res.getString("email"), res.getDouble("balance"));
            }
            System.out.println(users);
            if (users != null) {
                System.out.println("已存在，跳转登陆");
                return users;
            } else {
                System.out.println("不存在，开始注册");
                //进行注册
                sql = "insert into User(user_id,username,sex,mobile,qqcount_id,create_time,user_img) values(?,?,?,?,?,?,?)";
                prea = connection.prepareStatement(sql);
                prea.setString(1, user.getUserId());
                prea.setString(2, user.getUserName());
                prea.setString(3, user.getUserSex());
                prea.setString(4, user.getUserMobile());
                prea.setString(5, user.getUserQqcountId());
                prea.setString(6, user.getUserCreateTime());
                prea.setString(7, user.getUserImg());
                result = prea.executeUpdate();

                users = new User();
                users = getUserInfoByUserId(user.getUserId());

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(res, prea, null);
        }
        return users;
    }

    @Override
    public User getUserInfoByUserId(String userId) {
        User users = null;
        System.out.println("根据用户id查询用户信息开始");
        System.out.println(userId);
        connection = JdbcUtil.getConnection();
        try {
            sql = "select * from User where user_id=?";
            prea = connection.prepareStatement(sql);
            prea.setString(1, userId);
            res = prea.executeQuery();
            while (res.next()) {
                users = new User(res.getString("user_id"), res.getString("username"), null, res.getString("sex"), res.getString("mobile"), res.getString("qqcount_id"), res.getString("create_time"), res.getString("user_img"), res.getString("email"), res.getDouble("balance"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(res, prea, null);
        }
        return users;
    }


    //免密登陆或者手机号/用户名密码登陆

    /**
     * @description: 免密登陆或者手机号/用户名密码登陆
     * @param: 手机号 密码
     * @return: User
     * @author liyuxiang
     * @date: 2021/3/22 9:00 下午
     */
    @Override
    public User mobileLoginAndRegister(String mobile) {
        User users = null;
        connection = JdbcUtil.getConnection();
        System.out.println(connection);
        try {

            sql = "select * from User where mobile=?";
            prea = connection.prepareStatement(sql);
            prea.setString(1, mobile);
            res = prea.executeQuery();
            while (res.next()) {
                users = new User(res.getString("user_id"), res.getString("username"), null, res.getString("sex"), res.getString("mobile"), res.getString("qqcount_id"), res.getString("create_time"), res.getString("user_img"), res.getString("email"), res.getDouble("balance"));
            }
            if (users != null) {
                System.out.println("已存在，跳转登陆");
                System.out.println(users);
                return users;
                //跳转主页面
            } else {
                System.out.println("不存在，跳转注册");
                //进行注册
                //生成用户唯一id
                String uuid = null;
                for (int i = 0; i < 5; i++) {
                    //注意replaceAll前面的是正则表达式
                    uuid = UUID.randomUUID().toString().replaceAll("-", "");
                }
                sql = "insert into User(user_id,username,sex,mobile,create_time,user_img) values(?,?,?,?,?,?)";
                prea = connection.prepareStatement(sql);
                prea.setString(1, uuid);
                RandomUserNameUtil randomUserNameUtil = new RandomUserNameUtil();
                prea.setString(2, randomUserNameUtil.generateName());//随机产生一个用户名
                prea.setString(3, "男");//默认为男性
                prea.setString(4, mobile);//用户的手机号
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss");
                Date date = new Date(System.currentTimeMillis());
                String time = formatter.format(date);
                prea.setString(5, time);//注册时间
                String imgStr = "http://43.128.27.123:12100/group1/M00/00/00/rBMADmBlmZqAJZcfAAAgy0ihSvw435.png";
                prea.setString(6, imgStr);
                result = prea.executeUpdate();
                users = new User();
                users = getUserInfoByMobile(mobile);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(res, prea, null);
        }
        return users;
    }

    public User getUserInfoByMobile(String mobile) {
        User users = null;
        connection = JdbcUtil.getConnection();
        System.out.println(connection);
        try {
            sql = "select * from User where mobile=?";
            prea = connection.prepareStatement(sql);
            prea.setString(1, mobile);
            res = prea.executeQuery();
            while (res.next()) {
                users = new User(res.getString("user_id"), res.getString("username"), null, res.getString("sex"), res.getString("mobile"), res.getString("qqcount_id"), res.getString("create_time"), res.getString("user_img"), res.getString("email"), res.getDouble("balance"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(res, prea, null);
        }
        return users;
    }


    /**
     * @description: 获取用户人数
     * @param:
     * @return: int result
     * @author liyuxiang
     * @date: 2021/3/22 8:59 下午
     */
    public int getUserNumber() {
        connection = JdbcUtil.getConnection();
        try {
            sql = "select count(1) from User";
            prea = connection.prepareStatement(sql);
            res = prea.executeQuery();
            while (res.next()) {
                result = res.getInt(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(null, prea, connection);
        }
        return result;
    }

    /**
     * @description: 后台登陆
     * @param: 用户名和密码
     * @return: User
     * @author liyuxiang
     * @date: 2021/3/22 8:59 下午
     */
    public User adminLogin(String userName, String password) {
        User users = null;
        connection = JdbcUtil.getConnection();
        try {
            sql = "select * from User where username=? and password=?";
            prea = connection.prepareStatement(sql);
            prea.setString(1, userName);
            prea.setString(2, password);
            res = prea.executeQuery();
            if (res != null) {
                users = new User();
            }
            while (res.next()) {
                users.setUserName(res.getString("username"));
                users.setUserPassword(res.getString("password"));
                users.setUserId(res.getString("user_id"));

                users.setUserSex(res.getString("sex"));
                users.setUserImg(res.getString("user_img"));
                users.setUserEmail(res.getString("email"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            JdbcUtil.close(res, prea, null);
        }

        return users;
    }

    /**
     * @description: 获取用户信息   为空则查询全部
     * @param: 用户名
     * @return: List<User>
     * @author liyuxiang
     * @date: 2021/3/22 8:58 下午
     */
    @Override
    public List<User> getAllUserInfo(String username, int page, int limit) {
        User users = null;
        int userNumber = getUserNumber();
        int start = (page - 1) * limit;
        List<User> userList = null;
        connection = JdbcUtil.getConnection();
        try {
            System.out.println("用户名是：" + username);
            if (username == null || username.equals("")) {
                sql = "select * from User";
                prea = connection.prepareStatement(sql);
            } else {
                sql = "select * from User where INSTR(username, ?)";
                prea = connection.prepareStatement(sql);
                prea.setString(1, username);

            }
            res = prea.executeQuery();
            if (res != null) {
                userList = new ArrayList<User>();
            }
            while (res.next()) {
                users = new User(res.getString("user_id"), res.getString("username"), res.getString("password"), res.getString("sex"), res.getString("mobile"), res.getString("qqcount_id"), res.getString("create_time"), res.getString("user_img"), res.getString("email"), res.getDouble("balance"));
                userList.add(users);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(res, prea, connection);
        }
        return userList;
    }

    /**
     * @description: 删除用户    批处理
     * @param: 用户id数组
     * @return: int result
     * @author liyuxiang
     * @date: 2021/3/22 9:01 下午
     */
    @Override
    public int deleteUserInfo(int[] userId) {
        System.out.println(userId[0]);
        sql = "delete  from User where id in (?";
        StringBuffer sqlbuf = new StringBuffer(sql);
//        String sql = "delete  from `user` where u_id = ?";
        connection = JdbcUtil.getConnection();
        try {
            //拼接sqlbuf，两种情况
            if (userId.length == 1) {
                //有1条时， 直接加 "）"结束
                sqlbuf.append(")");
            } else {
                //有多条时候，拼接length-1 次，因为初始sql语句已经有一次了。"delete  from `user` where u_id in (? "
                for (int i = 0; i < userId.length - 1; i++) {
                    sqlbuf.append(",?");

                }
                //最后拼接" )"  圆满完成拼接sql
                sqlbuf.append(")");
            }
            System.out.println(sqlbuf.toString());
            this.prea = connection.prepareStatement(sqlbuf.toString());
            if (userId.length == 1) {
                prea.setInt(1, userId[0]);
            } else {

                for (int i = 1; i <= userId.length; i++) {
                    prea.setInt(i, userId[i - 1]);
                    //userids[i-1] 因为数据下标从0 开始。
                }
            }

            return prea.executeUpdate();

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            this.close(null, prea, connection);
        }
        return 0;
    }

    /**
     * @description: 修改密码
     * @param:
     * @return:
     * @author liyuxiang
     * @date: 2021/4/8 4:33 下午
     */
    @Override
    public int changePassword(String userId, String password) {
        System.out.println(userId);
        connection = JdbcUtil.getConnection();
        try {
            sql = "update User set password=? where user_id=?";

            prea = connection.prepareStatement(sql);
            prea.setString(1, password);
            prea.setString(2, userId);
            result = prea.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            this.close(null, prea, connection);
        }
        return result;
    }
    //根据文章id拿到数据



    @Override
    public List<Article> getUserIdInfoByUser(String articleId) {
            List<Article> articleList=null;
        connection = JdbcUtil.getConnection();
        try {
            sql = "SELECT * from Article as a,`User` as u where a.article_id=? and a.article_author=u.user_id";

            prea = connection.prepareStatement(sql);
            prea.setString(1, articleId);

            res = prea.executeQuery();
            while(res.next()){
                if(articleList==null){
                    articleList=new ArrayList<Article>();
                }

                int articleIds = res.getInt(1);
                String articleTitle = res.getString(2);

                /*SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                String articleTime = sim.format(res.getDate("article_time"));*/
                String articleImg = res.getString(3);
                String articleAuthor = res.getString(4);
                String authorImg = res.getString(5);
                String articleContent = res.getString(6);
//                int articleType = res.getInt(7);
                String articleTypes=res.getString(12);
                int articleLike = res.getInt(9);
//                System.out.println(res.getInt("article_like"));
                int articleBrowse = res.getInt(10);
                User user=new User(res.getString(22), res.getString(13), null, res.getString(15), res.getString(23), res.getString(29), res.getString(30), res.getString(27), res.getString(24), res.getDouble(17));

                Article article = new Article();
                article.setArticleId(articleIds);
                article.setArticleAuthor(articleAuthor);
//                article.setArticleBrowse(articleBrowse);
                article.setArticleContent(articleContent);
                article.setArticleImg(articleImg);
//                article.setArticleLike(articleLike);
                //article.setArticleTime(articleTime);
                article.setArticleType(articleTypes);
                article.setAuthorImg(authorImg);
                article.setArticleTitle(articleTitle);
                article.setUser(user);
                articleList.add(article);


            }

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            this.close(null, prea, connection);
        }
        return articleList;




    }
    //用户修改信息

    @Override
    public int updateUserManager(String userId, User user) {
        connection = JdbcUtil.getConnection();
        try {
            sql = "UPDATE `User` SET username=? ,mobile=?,email=?,sex=?,`profile`=?WHERE user_id=?";
            prea = connection.prepareStatement(sql);
            prea.setString(1,user.getUserName());
            prea.setString(2,user.getUserMobile());
            prea.setString(3,user.getUserEmail());
            prea.setString(4,user.getUserSex());
            prea.setString(5,user.getProfile());
            prea.setString(6,userId);
            result = prea.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(null, prea, connection);
        }
        return result;
    }

    @Override
    public User mobileAndPassLogin(String mobile, String pass) {
        User user = null;
        connection = JdbcUtil.getConnection();
        try {
            sql = "select * from User where mobile=? and password=?";
            prea = connection.prepareStatement(sql);
            prea.setString(1, mobile);
            prea.setString(2, pass);
            res = prea.executeQuery();
            while (res.next()) {
                user = new User(res.getString("user_id"), res.getString("username"), null, res.getString("sex"), res.getString("mobile"), res.getString("qqcount_id"), res.getString("create_time"), res.getString("user_img"), res.getString("email"), res.getDouble("balance"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            JdbcUtil.close(res, prea, connection);
        }
        return user;
    }

    @Override
    public int addUserCb(String userId, int cb) {
        connection = JdbcUtil.getConnection();
        try {
            sql = "update User set cb=cb+? where user_id=?";
            prea = connection.prepareStatement(sql);
            prea.setInt(1, cb);
            prea.setString(2,userId);
            result=prea.executeUpdate();
            System.out.println(result);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            JdbcUtil.close(null, prea, null);
        }
        return result;
    }

    @Override
    public int getUserCbByUserId(String userId) {
        connection = JdbcUtil.getConnection();
        try {
            sql = "select * from User where user_id=?";
            prea = connection.prepareStatement(sql);
            prea.setString(1,userId);
            res=prea.executeQuery();
            while (res.next()){
                result = res.getInt("cb");
            }
            System.out.println(result);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            JdbcUtil.close(null, prea, connection);
        }
        return result;
    }
}
